<?php
/**
 * Created by PhpStorm.
 * User: front
 * Date: 2018/8/8
 * Time: 14:38
 */

namespace App\Api\Admin\Controllers;

use App\Exceptions\ApiException;
use App\Jobs\Elesticsearch;
use App\Models\Admin\Log;
use App\Models\Media;
use App\Models\MediaComment;
use App\Models\MediaRecommend;
use App\Models\MediaStar;
use App\Models\Report;
use App\Models\User;
use App\Models\Music;
use App\Models\UserDynamicList;
use App\Models\MusicType;
use App\Models\AdminUser;
use App\Services\MusicService;
use App\Services\MediaService;
use App\Services\OSS;
use App\Services\Sts;
use DateTime;
use App\Models\Admin\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\MusicBackGroundService;
use App\Services\PinyinService;
use App\Models\MusicBackground;
use Illuminate\Support\Facades\Redis;

class MediaController extends CommonController
{

    public function __construct()
    {
        parent::__construct();

    }

    /**
     * 视频列表
     * @param Request $request
     * @return array
     */
    public function mediaList(Request $request)
    {
        $title =$request->input('title');  // 视频标题
        $name  = $request->input('name');   // 用户昵称
        $uid = $request->input('uid'); // 用户id
        $mobie = $request->input('mobile'); // 用户id
        $media_type = $request->input('is_private'); // 视频类型
        /*$status = $request->input('status'); // 视频状态 0：审核不通过  1：审核通过  2：待审核
          $status = !isset($status) || !in_array((int) $status, [0, 1, 2]) ? 1 : $status;
          $is_delete = (int) $request->input('is_delete');
          $is_delete = $is_delete ? 1 : 0;*/
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
        $where = [ ['media.is_delete',0], ['media.is_forward',0]];
        $fields = ['media.id', 'media.uid', 'media.title', 'media.media', 'media.screenwriter', 'media.staring', 'media.player', 'media.director', 'media.pv', 'media.comments', 'media.star', 'media.sorts', 'media.like', 'media.share','media.status', 'media.remarks', 'media.created_at', 'media.updated_at', 'media.is_like', 'media.cover','media.is_delete','media.is_private', 'media.video_length', 'users.id as uid', 'users.name as uname','users.mobile'];
        if ($title) {
            $where[] = ['media.title', 'like', '%' . $title . '%'];
        }
        if(!empty($media_type)){
            $where[] = ['media.is_private','=',$media_type];
        }
        if ($mobie) {
            $where[] = ['users.mobile', 'like', '%' . $mobie . '%'];
        }
        if ($name) {
            $where[] = ['users.name', 'like', '%' . $name . '%'];
        }
        if ($uid) {
            $where[] = ['uid', 'like','%'. $uid .'%'];
        }
        $lists = Media::where($where)->whereIn('media.status', [0,1])->join('users', 'users.id', '=', 'media.uid')->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        $total = Media::where($where)->whereIn('media.status', [0,1])->join('users', 'users.id', '=', 'media.uid')->count();
        $totalPage = ceil($total / $pagesize);
        foreach ($lists as $key=>$value) {
            $lists[$key]['y_media'] = $value['media'];
            $lists[$key]['media'] = getSignUrl($value['media']);
            $lists[$key]['cover'] = getSignUrl($value['cover']);
        }
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $lists]);
    }

    /***
     * @param Request $request
     * @return array
     * 视频详情
     */
    public function details(Request $request)
    {
        $id= IT('id',true,'请上传视频id');
        $fields = ['media.id', 'media.uid', 'media.title', 'media.media','media.tags','media.share', 'media.screenwriter', 'media.staring', 'media.player', 'media.director', 'media.pv', 'media.comments', 'media.star', 'media.sorts', 'media.like', 'media.status', 'media.remarks', 'media.created_at', 'media.updated_at', 'media.is_like', 'media.cover', 'media.video_length', 'users.name as uname'];
        $data = Media::where(['media.id'=>$id,'media.is_delete'=> 0])->join('users', 'users.id', '=', 'media.uid')->first($fields);
        if(!$data){
            return json_error('视频不存在');
        }
        $arr =explode(",",$data['tags']);
        $data->tags_name = D('tags_name')->whereIn('id',$arr)->get(['id','tags_name']);
        // $where_status = [ ['parent_id','<>',0], ['status', 1], ['media_comment.is_delete', 0], ['media_id', $id] ];
        $data->original_cover =  $data->cover;
        $data->original_media =  $data->media;
        $data->cover = getSignUrl($data->cover);
        $data->media = getSignUrl($data->media);
        $data->player = array_to_object(json_decode($data->player));
        $data->director = array_to_object(json_decode($data->director));
        if(!empty($data->cover ) && !empty($data->media)){
            $media_arr = explode('/', explode('.com/',$data->original_media)[1]);
            $temp_arr = explode('/', explode('.com/',$data->original_cover)[1]);
            $data->cover_cover = end($temp_arr);
            $data->media_cover = end($media_arr);
            unset($temp_arr[count($temp_arr)-1]);
            unset($media_arr[count($media_arr)-1]);
            $media_dir = implode('/', $media_arr).'/';
            $media_oss = OSS::create_oss_token($media_dir);
            $cover_dir = implode('/', $temp_arr).'/';
            $cover_oss = OSS::create_oss_token($cover_dir);
            $data->media_oss = $media_oss;
            $data->cover_oss = $cover_oss;
        }
        return json_success('ok',$data);
    }

    public function MediaEdit(Request $request)
    {
        $id = IT('id',true,'请输入视频id');
        $title= IT('title');
        $media = IT('media');
        $cover_file = IT('cover');
        $tags= IT('tags');
        $video_length = IT('video_length');
        $staring = IT('staring');
        $director = IT('director');
        $media_data = Media::where(['id'=>$id,'is_delete'=> 0])->first();
        if(!$media_data){
            return json_error('该视频不存在');
        }
        if ($staring) {
            $staring = json_encode(explode(',', trim($staring, ',')), JSON_UNESCAPED_UNICODE);
            if (!is_json($staring)) {
                return json_error('主演格式错误');
            }
        }
        if ($director) {
            $director = json_encode(explode(',', trim($director, ',')), JSON_UNESCAPED_UNICODE);
            if (!is_json($director)) {
                return json_error('导演格式错误');
            }
        }
        if(!empty($title) && $title != $media_data->title ){
            $media_data->title = $title;
        }
        if(!empty($media) && $media != $media_data->media ){
            $media_data->media = clear_urlcan($media);
        }
        if(!empty($cover_file) && $cover_file != $media_data->cover){
            $media_data->cover = clear_urlcan($cover_file);
        }
        if(!empty($tags) && $tags != $media_data->tags ){
            $media_data->tags = $tags;
        }
        if(!empty($video_length) && $video_length != $media_data->video_length ){
            $media_data->video_length = $video_length;
        }
        if(!empty($staring) && $staring != $media_data->staring ){
            $media_data->player = $staring;
        }
        if(!empty($director) && $director != $media_data->director ){
            $media_data->director = $director;
        }
        $update = $media_data->save();
        // $update= Media::save($update_media);
        if($update){
            (new Log)->add($this->user,'修改了视频'.'视频id为-'.$id);
            return json_success('修改成功');
        }else{
            return json_error('修改失败');
        }
    }


    /**
     * 举报列表
     * @param Request $request
     * @return array
     */
    public function getReport(Request $request)
    {
        $report_type = $request->input('report_type');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pageszie');
        $pagesize = $pagesize ? : 10;
        $offset = ($page - 1) * $pagesize;
        $reports_number = $request->input('reports_number');
        if($report_type){
            $where =  ['media_report.status'=>1, 'media_report.report_type'=>$report_type] ;
        }else{
            $where =  ['media_report.status'=>1];
        }
        $list = Report::where($where)->with('media')->with('user')->with('report_type')->groupBy('media_id')->orderBy('report_time','desc')->paginate($pagesize);
        $temp_arr = [];
        $list_data = [];
        foreach ($list as &$report){
            $report_time = Report::where('media_id', $report['media_id'])->max('report_time');
            $report_max = Report::where('report_time',$report_time)->first();
            $report_name = D('report_type')->where('id','=', $report_max['report_type'])->value('name');
            $temp_arr['id'] = $report['media_id'];
            $temp_arr['report_type'] =  empty($report_name) ? '' : $report_name ;
            $temp_arr['report_time'] = $report_time;
            $temp_arr['media'] =  (!empty($report['media']) && !empty($report['media']->media)) ? getSignUrl($report['media']->media) : '';
            $temp_arr['cover'] = (!empty($report['media']) && !empty($report['media']->cover)) ? getSignUrl($report['media']->cover) : '';
            $temp_arr['content'] =  empty($report['content']) ? '' :$report['content'];
            $temp_arr['uid'] = empty($report['user']['id']) ? '' :  $report['user']['id'];
            $temp_arr['name'] = empty($report['user']['name']) ? '' :  $report['user']['name'];
            $temp_arr['title'] = empty( $report['media']['title']) ? '': $report['media']['title'];
            $temp_arr['created_at'] = empty($report['media']['created_at']) ? '' : $report['media']['created_at'] ;
            $temp_arr['video_length'] =empty( $report['media']['video_length']) ? '' : $report['media']['video_length'];
            $temp_arr['reports_number'] = D('media_report')->where('media_id',$report['media_id'])->count();
            $list_data[] = $temp_arr;
        }
      //按照举报次数重新排序
        if($reports_number){
            foreach ($list_data as $key => $row)
            {
                $volume[$key]  = $row['reports_number'];
            }
            if($reports_number=='desc'){
                array_multisort($volume, SORT_DESC, $list_data);
            }elseif ($reports_number=='asc'){
                array_multisort($volume, SORT_ASC, $list_data);
            }
        }
        unset($report);
        return json_success('ok', ['total'=>$list->total(),'totalPage' => $list->lastPage(),'list' => $list_data ]);
    }

    /**
     * @param Request $request
     * 举报详情
     */

    public  function ReportDetails(Request $request){
        $media_id = IT('media_id', true, '请选择视频');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pageszie');
        $pagesize = $pagesize ?: 3;
        $offset = ($page - 1) * $pagesize;
        $media = Media::find($media_id);
        if (!$media) {
            return json_error('视频不存在');
        }
        $reports = Report::where('media_id',$media_id)->with('media')->with('user')->with('report_type')->paginate($pagesize);
        $temp_arr = [];
        $list_data = [];
        foreach ($reports as &$report){
            $report_name = D('report_type')->where('id','=', $report['report_type'])->value('name');
            $temp_arr['id'] = $report['id'];
            $temp_arr['uid'] = empty($report['user']['id']) ? '' :  $report['user']['id'];
            $temp_arr['title'] = empty( $report['media']['title']) ? '': $report['media']['title'];
            $temp_arr['media'] =  (!empty($report['media']) && !empty($report['media']->media)) ? getSignUrl($report['media']->media) : '';
            $temp_arr['cover'] = (!empty($report['media']) && !empty($report['media']['cover'])) ? getSignUrl($report['media']['cover']) : '';
            $temp_arr['avatar'] = empty($report['user']['avatar'])? '' : getSignUrl($report['user']['avatar']);
            $temp_arr['created_at'] = empty($report['media']['created_at']) ? '' : $report['media']['created_at'];
            $temp_arr['video_length'] =empty( $report['media']['video_length']) ? '' : $report['media']['video_length'];
            $temp_arr['report_type'] = empty($report_name) ? '' : $report_name ;
            $temp_arr['content'] = empty($report['content']) ? '' : $report['content'] ;
            $temp_arr['report_time'] = empty($report['report_time']) ? '' : $report['report_time'];
            $temp_arr['status'] = empty($report['status']) ? '' : $report['status'];
            $temp_arr['name'] = User::where('id',$report->uid)->first(['name']);
            $temp_arr['reports_number'] = D('media_report')->where('media_id',$temp_arr['id'])->count();
            $list_data[] = $temp_arr;
        }
        $arr =explode(",",$media->tags);
        $tags_name = D('tags_name')->whereIn('id',$arr)->select('tags_name')->get();
        $media_info=[
            'title' => $media->title,
            'player' =>$media->player,
            'staring'=> $media->staring,
            'director' =>$media->director,
            'media' => getSignUrl($media['media']),
            'cover' => getSignUrl($media['cover']),
            'screenwriter' =>$media->screenwriter,
            'tags' => $tags_name,
            'created_at' => $media->created_at,
            'report_time' =>D('media_report')->where('media_id',$media_id)->MAX('report_time'),
            'reports_number' => Report::where('media_id',$media_id)->count()
        ];
        return json_success('ok', ['total'=>$reports->total(),'totalPage' => $reports->lastPage(), 'list' => $list_data,'media_info' =>$media_info]);
    }

    /**
     * 举报删除
     *
     */
    public  function DelReport(){
       // $id  = IT('id', true, '请输入ID');
        $id  = IT('id',true,'请输入视频ID');
        //切割多选ID，
        /*   $str_id = explode(",",$id);
           foreach ($str_id as $k){
                    $data =  D('media_report')->where('id','=',$k)->delete();
              }*/
        $str_mediaid =explode(",",$id);
        foreach ($str_mediaid as $k){
            Report::where('media_id','=',$k)->update(['status'=>0]);
            $data =  Media::where('id','=',$k)->update(['is_delete'=>1]);
            // 删除动态
            D("ivy_user_dynamiclist")->where('media_id','=',$k)->update(['status'=>0]);
            // 删除评论
            MediaComment::where([['media_id','=',$k],['is_delete','=',0]])->update(['is_delete'=>1, 'status' => 0]);
            // 删除转发的视频
            $is_record = Media::where([['is_forward' ,'=', 1], ['parent_id', '=', $k], ['is_delete', '=', 0]])->first();
            if($is_record) {
                Media::where([['is_forward', '=', 1], ['parent_id', '=', $k],['is_delete', '=', 0]])->update(['is_delete'=>1]);
            }
        }
        if($data){
            (new Log)->add($this->user, '删除了视频视频id为-'.$id.'的举报');
            return json_success('ok');
        }else{
            return json_error('删除失败');
        }
    }


    /**
     * 视频对应的评论
     * @param Request $request
     * @return array
     */
    public function getComment(Request $request)
    {
        $media_id = IT('media_id', true, '请选择视频');
        $page = max(1, (int) $request->input('page'));
        $content = $request->input('content');
        $pagesize = (int) $request->input('pageszie');
        $pagesize = $pagesize ?: 3;
        $offset = ($page - 1) * $pagesize;
        $parent_id = $request->input('parent_id');

        $media = Media::find($media_id);

        if (!$media) {
            return json_error('视频不存在');
        }
        if ($content) {
            $where[] = ['content', 'like', '%' . $content . '%'];
        }
        $where_status = [ ['media_comment.status', 1], ['media_comment.is_delete', 0], ['media_id', $media_id],['media_comment.parent_id', 0] ];
        $fields = ['media_comment.id', 'content', 'media_comment.created_at', 'users.name', 'users.avatar'];
        if(!empty($content)){
            $total =MediaComment::where($where)->where($where_status)->join('users', 'media_comment.uid', '=', 'users.id')->count();
            $comments = MediaComment::where($where)->where($where_status)->join('users', 'media_comment.uid', '=', 'users.id')->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        }elseif(!empty($parent_id)){
            $where_Reply = [ ['media_comment.status', 1], ['media_comment.is_delete', 0],['media_comment.parent_id',$parent_id]];
            $total =MediaComment::where($where_Reply)->join('users', 'media_comment.uid', '=', 'users.id')->count();
            $comments = MediaComment::where($where_Reply)->join('users', 'media_comment.uid', '=', 'users.id')->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        } else{
            $total =  MediaComment::where($where_status)->join('users', 'media_comment.uid', '=', 'users.id')->count();
            $comments = MediaComment::where($where_status)->join('users', 'media_comment.uid', '=', 'users.id')->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        }

        $totalPage = ceil($total / $pagesize);
        /* if ($parent_id === 0) {
             $sub_comments = MediaComment::where([['media_id', $media_id], ['status', 1], ['is_delete', 0]])->get();

             $comment_ids = [];
             foreach ($comments as $comment) {
                 $comment_ids[] = $comment->id;
                 $comment->sub_comments = 0;
                 $comment->avatar = getSignUrl($comment->avatar);
                 $comment->Reply_number = D('media_comment')->where('media_id',$media_id)->where('parent_id',$comment->id)->count();
             }
             if (!empty($comment_ids)) {
                 foreach ($sub_comments as $comment) {
                     if ($index = array_search($comment->parent_id, $comment_ids)) {
                         $comments[$index]->sub_comments += 1;
                     }
                 }
             }
         }*/
        foreach ($comments as $comment) {
            $comment->Reply_number = D('media_comment')->where('media_id',$media_id)->where('parent_id',$comment->id)->count();
            $comment->avatar = getSignUrl($comment->avatar);
        }
        return json_success('ok', ['totalpage' => $totalPage,'total'=>$total, 'list' => $comments,]);
    }

    /**
     * 删除评论
     * @return array
     */
    public function deleteComment()
    {
        $comment_id = IT('comment_id', true, '请选择要删除的评论');

        $comment = MediaComment::find($comment_id);
        if (!$comment || $comment->is_delete == '1' || $comment->status != '1') {
            return json_error('评论不存在');
        }

        $is_forward = false;
        if($comment->type == 1) {
            $is_forward = true;
        }
        DB::beginTransaction();
        $res = true;
        $comment->is_delete = 1;
        $res = $res && false !== $comment->save();
        $res = $res && false !== DB::table('media')->where('id', $comment->media_id)->decrement('comments', 1);

        if (!$res) {
            DB::roolback();
            return json_error('删除评论失败，稍后再试');
        }

        // 删除转发视频
        if($is_forward) {
            $is_record = Media::where([['is_forward' ,'=', 1], ['forward_id', '=', $comment_id], ['is_delete', '=', 0]])->first();
            if($is_record) {
                Media::where([['is_forward', '=', 1], ['forward_id', '=', $comment_id], ['is_delete', '=', 0]])->update(['is_delete'=>1]);
            }
        }

        DB::commit();
        (new Log)->add($this->user, '删除了一条评论，评论id为“'.$comment_id.'”');
        return json_success('ok');
    }

    /**
     * 审核视频
     * @param Request $request
     * @return array
     */
    public function changeStatus(Request $request)
    {
        $media_id = IT('media_id', true, '请选择视频');
        $status = IT('status', true, '请选择状态');

        $reason = $request->input('reason');
        $reason = $reason ?: '';

        if (!in_array($status, ['1', '2'])) {
            return json_error('审核状态有误');
        }

        $media = Media::find($media_id);
        $is_read = $status === '2' ? 0 : 1;

        if (!$media || $media['is_delete'] == '1') {
            return json_error('审核影片不存在');
        }

        if ($status === '2' && !$reason) {
            return json_error('请填写审核失败原因');
        }

        DB::beginTransaction();
        $res = true;
        $media->status = $status;
        $res = $res && false !== $media->save();

        $res = $res && DB::table('media_verify')->insert(['media_id' => $media_id, 'uid' => $media->uid, 'status' => $status, 'reason' => $reason, 'admin_uid' => $this->user['id'], 'create_at' => date('Y-m-d H:i:s'), 'is_read' => $is_read]);

        if (!$res) {
            DB::rollback();
            return json_error('审核失败，请稍后再试');
        }

        DB::commit();
        (new Log)->add($this->user, '审核视频，视频id为' . $media_id . ', 标题为“'. $media->title .'”');
        return json_success('ok');
    }

    /**
     * @param Request $request
     * 待审核视频列表
     * @return array
     */
    public function  checkupList(Request $request){
        $title = $request->input('title');  // 视频标题
        $name  = $request->input('name');   // 用户昵称
        $uid = (int) $request->input('uid'); // 用户id
        $is_delete = (int) $request->input('is_delete');
        $is_delete = $is_delete ? 1 : 0;
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
        $where = [ ['media.status', '=', 2], ['media.is_delete', '=', $is_delete] ];
        $fields = ['media.id', 'media.uid', 'media.title', 'media.media', 'media.screenwriter', 'media.staring', 'media.player', 'media.director', 'media.pv', 'media.comments', 'media.star', 'media.sorts', 'media.like', 'media.status', 'media.remarks', 'media.created_at', 'media.updated_at', 'media.is_like', 'media.cover', 'media.video_length', 'users.name as uname'];
        if ($title) {
            $where[] = ['media.title', 'like', '%' . $title . '%'];
        }
        if ($name) {
            $where[] = ['users.name', 'like', '%' . $name . '%'];
        }
        if ($uid) {
            $where[] = ['media.uid', '=', $uid];
        }
        $lists = Media::where($where)->join('users', 'users.id', '=', 'media.uid')->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        $total = Media::where($where)->join('users', 'users.id', '=', 'media.uid')->count();
        $totalPage = ceil($total / $pagesize);
        // 获取内网视频图片链接
        $datetime = new DateTime();
        $datetime->modify('+1 day');
        foreach ($lists as &$list) {
            $list->media = getSignUrl($list->media);
            $list->cover = getSignUrl($list->cover);
        }
        unset($list);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $lists]);
    }

    /**
     * @return array
     * 审核不通过的原因列表
     */
    public function AuditReasons(){
        //  $data= config('admin.report_status');
        $data =D('report_type')->get(['id','name']);
        return json_success('ok',$data);
    }
    /**
     * @param Request $request
     * 审核不通过
     * @return array
     */
    public function NotThrough(Request $request){
        $title = $request->input('title');  // 视频标题
        $name  = $request->input('name');   // 用户昵称
        $uid = (int) $request->input('uid'); // 用户id
        $is_delete = (int) $request->input('is_delete');
        $is_delete = $is_delete ? 1 : 0;
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
        $where = [ ['media.status', '=', 0], ['media.is_delete', '=', $is_delete] ];
        $fields = ['media.id', 'media.uid', 'media.title', 'media.media', 'media.screenwriter', 'media.staring', 'media.player', 'media.director', 'media.pv', 'media.comments', 'media.star', 'media.sorts', 'media.like', 'media.status', 'media.remarks', 'media.created_at', 'media.updated_at', 'media.is_like', 'media.cover', 'media.video_length', 'users.name as uname','media_verify.reason'];
        if ($title) {
            $where[] = ['media.title', 'like', '%' . $title . '%'];
        }
        if ($name) {
            $where[] = ['users.name', 'like', '%' . $name . '%'];
        }
        if ($uid) {
            $where[] = ['media.uid', '=', $uid];
        }
        $lists = Media::where($where)->join('users', 'users.id', '=', 'media.uid')->join('media_verify', 'media_verify.media_id', '=', 'media.id')->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get($fields);
        $total = Media::where($where)->join('users', 'users.id', '=', 'media.uid')->join('media_verify', 'media_verify.media_id', '=', 'media.id')->count();
        $totalPage = ceil($total / $pagesize);
        // 获取内网视频图片链接
        $datetime = new DateTime();
        $datetime->modify('+1 day');
        foreach ($lists as &$list) {
            $list->media = getSignUrl($list->media);
            $list->cover = getSignUrl($list->cover);
        }
        unset($list);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $lists]);
    }
    public function mediaUpload(Request $request)
    {
        $cover_file = IT('cover', true, '请上传封面');
        $media = IT('media',true, '请上传视频');
        $tags= IT('tags',true,'请选择影片分类');
        $uid = IT('uid', true, '请选择用户');
        $title = IT('title', true, '请填写视频标题');
        $video_length = IT('video_length', true, '请填写视频时长');
        $staring = IT('staring');
        $director = IT('director');
        $user = User::find($uid);
        if (!$user || $user->status != '1') {
            return json_error('用户不存在');
        }
        if ($staring) {
            $staring = json_encode(explode(',', trim($staring, ',')), JSON_UNESCAPED_UNICODE);
            if (!is_json($staring)) {
                return json_error('主演格式错误');
            }
        }
        if ($director) {
            $director = json_encode(explode(',', trim($director, ',')), JSON_UNESCAPED_UNICODE);
            if (!is_json($director)) {
                return json_error('导演格式错误');
            }
        }
        if(empty($media)){
            return json_error('视频不能为空');
        }
        if(empty($cover_file)){
            return json_error('封面不能为空');
        }
        //视频，封面连接过滤
        $media  = clear_urlcan($media);
        $cover  = clear_urlcan($cover_file);
        $data = [
            'uid' => $uid,
            'title' => $title,
            'media' =>$media,
            'staring' => $staring,
            'director' => $director,
            'video_length' => $video_length,
            'cover' =>$cover,
            'date' => date('Y-m-d'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'tags' => $tags
        ];
        $media_data = Media::insertGetId($data);
        if($media_data){
            (new Log)->add($this->user, '上传了视频' . ', 视频ID为' . $media_data .'-名称为 '.$title. '');
            //视频上传成功入队--添加搜索索引
            $temp_arr = [];
            $temp_arr['mid'] = $media_data;
            $temp_arr['title'] = $title;
            $temp_arr['description'] = $title;
            $temp_arr['cover'] = $cover;
            dispatch((new Elesticsearch(['type'=>'2', 'action'=>'add', 'data'=>$temp_arr]))->onQueue('eleasticsearch'));
            return json_success('ok');
        }else{
            return json_error('上传失败');
        }
    }
    /**
     * 获取网页上传OSS签名
     * @param Request $request
     * @return array
     * @throws ApiException
     */
    public function getWapUploadToken(Request $request)
    {
        $userTicket = AdminUser::where('id','=', $this->user['id'])->first();
        if ($userTicket) {
            $uid = $userTicket->id;
        } else {
            throw new ApiException('参数有误', 0);
        }
        $id = env('WEB_ACCESS_ID');
        $key = env('WEB_ACCESS_KEY');
        $host = 'http://'.env('WEB_BUCKET_NAME').'.'.env('WEB_ENDPOINT');

        $now = time();
        $expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end);

        $dir = substr(md5($uid), 0, 4) . '/' . date('Ym') . '/';

        //最大文件大小.用户可以自己设置
        $condition = ['content-length-range', 0, 104857600];
        $conditions[] = $condition;

        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $start = ['starts-with', '$key', $dir];
        $conditions[] = $start;
        $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));
        $response = array();
        $response['filename'] = date('Ymd') . md5(uniqid()) ;
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        //这个参数是设置用户上传指定的前缀
        $response['dir'] = $dir;

        return json_success('ok', $response);
    }

    private function gmt_iso8601($time) {
        $dtStr = date("c", $time);
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }
    public function ConfirmUpload(){
        $img_file = IT('img_file', true, '请上传封面');
        if (!strpos($img_file, 'oss-cn-shenzhen.aliyuncs.com')) {
            return json_error('参数有误');
        }
        $img_file = getSignUrl($img_file);
        $return = array(
            'img_url' => $img_file
        );
        return json_success('上传成功', $return);
    }
    public function VideoUpload(Request $request){
        $video_file = IT('video_file', true, '请上传视频');
        /*$video_format = IT('video_format', true, '请上传视频格式');
        $video_file= $video_file.$video_format;*/
        if (!strpos($video_file, 'oss-cn-shenzhen.aliyuncs.com')) {
            return json_error('参数有误');
        }
        $video_file = getSignUrl($video_file);
        $return = array(
            'video_url' => $video_file
        );
        return json_success('上传成功', $return);
    }
    /**
     * @return array
     * 视频删除
     */
    public function DelMedia(){
        $media_id = IT('media_id',true,'请输入视频ID');
        $str = explode(",",$media_id);
        foreach ($str as $k){
            $list = Media::whereIn('id',$str)->update(['is_delete'=>1]);
            MediaComment::where('media_id','=',$k)->update(['status'=>0,'is_delete'=>1]);
            D("ivy_user_dynamiclist")->where('media_id','=',$k)->update(['status'=>0]);
            // 删除转发视频
            $is_record = Media::where([['is_forward' ,'=', 1], ['parent_id', '=', $k], ['is_delete', '=', 0]])->first();
            if($is_record) {
                Media::where([['is_forward', '=', 1], ['parent_id', '=', $k], ['is_delete', '=', 0]])->update(['is_delete'=>1]);
            }
        }
        if($list!==false) {

            $media_service = new MediaService();
            $result = $media_service->del_recommend($media_id);

            (new Log)->add($this->user, '删除了视频id为-'.$media_id);
            return json_success("ok");
        }else{
            return json_error('删除失败！');
        }
    }
    /**
     * @return array
     * 视频启用禁用
     */
    public function MediaEnable()
    {
        $media_id = IT('media_id',true,'请输入视频ID');
        $status = IT('status',true,'请输入状态');
        $check_media = Media::where('id',$media_id)->first();
        if(!$check_media){
            return json_error('视频不存在');
        }

        //禁用
        if($status == 0){
            $state_value ='禁用';
            D("ivy_user_dynamiclist")->where(['media_id'=>$media_id])->where('uid','<>',$check_media->uid)->update(['status'=>0]);
            $number = MediaStar::where(['media_id'=>$check_media->id,])->update(['status'=>0]);
            $list = Media::where('id',$media_id)->update(['status'=>0]);
            if($check_media->star > 0){
                Media::where('id',$media_id)->decrement('star',$number);
            }
            // 禁用转发视频
            $is_record = Media::where([['is_forward' ,'=', 1], ['parent_id', '=', $media_id], ['is_delete', '=', 0]])->first();
            if($is_record) {
                Media::where([['is_forward' ,'=', 1], ['parent_id', '=', $media_id], ['is_delete', '=', 0]])->update(['status'=>0]);
            }
            $media_service = new MediaService();
            $result = $media_service->del_recommend($media_id);
        }
        //启用
        if ($status == 1){
            $state_value ='启用';
            D("ivy_user_dynamiclist")->where(['media_id'=>$media_id])->where('uid','<>',$check_media->uid)->update(['status'=>1]);
            $number = MediaStar::where(['media_id'=>$check_media->id])->update(['status'=>1]);
            Media::where('id',$media_id)->increment('star',$number);
            $list = Media::where('id',$media_id)->update(['status'=>1]);
            // 启用转发视频
            $is_record = Media::where([['is_forward' ,'=', 1], ['parent_id', '=', $media_id], ['is_delete', '=', 0]])->first();
            if($is_record) {
                Media::where([['is_forward' ,'=', 1], ['parent_id', '=', $media_id], ['is_delete', '=', 0]])->update(['status'=>1]);
            }
        }
        if($list!==false) {
            (new Log)->add($this->user, '修改视频状态为-'.$state_value.'-视频id为-'.$media_id);
            return json_success("ok");
        }else{
            return json_error('失败！');
        }
    }
    /**
     * 音乐列表
     * @param Request $request
     * @return array
     */
    public function MusicList(Request $request){
        $category = $request->input('category');
        $page = intval($request->input('page')) ?: 1;
        $page = $page - 1;
        $pageSize =  intval($request->input('pageSize')) ?: 15;
        $name = $request->input('name');
        $Music_sequencing = $request->input('sequencing');
        $where = [];
        if ($name) {
            $where[] = ['music_name', 'like', '%' . $name . '%'];
        }
        if($category){
            $where[] = ['category', '=',$category];
        }
        $where['is_delete'] = 0;
        $status = $request->input('status');
        if($status === 0 || $status === 1) {
            $where[] = ['status', '=', $status];
        }
        $total = Music::where($where)->count();
        $totalPage = ceil($total / $pageSize);
        $music_data =Music::where($where)->skip($page * $pageSize)->take($pageSize)->orderBy('sort','asc')->orderBy('number','desc')->get(['id','music_name','music_link','category','time_length','created_at','sort','status','number']);
        //应用次数排序
        if($Music_sequencing ==1){
            $music_data =Music::where($where)->skip($page * $pageSize)->take($pageSize)->orderBy('number','desc')->get(['id','music_name','music_link','category','time_length','created_at','sort','status','number']);
        }
       // $music_initials  = new PinyinService();
        foreach ($music_data as &$list) {
            $list->music_link = getSignUrl($list->music_link);
            $list->category_id = $list->category;
            $list->category = D('music_type')->where('id','=',$list->category)->value('name');
       //     $list->music_initials = $music_initials->getFirstChar($list->music_name);
        }
        unset($list);
        return json_success("ok",['total'=>$total,'totalPage' => $totalPage, 'list' => $music_data]);
      }

      /**
       * 音乐类别
       * @return array
       */
    public function MusicType(){
        $type_data = MusicType::where(['status'=>0,'enable'=>1])->get(['id','name']);
        return json_success("ok",$type_data);

    }

    /**
     * 音乐上传
     * @return array
     *
     */
    public function MusicUpload(){
        $music_name= IT('music_name', true,'请填写音乐名称');
        $music_link= IT('music_link',true, '请填写音乐链接地址');
        $category= IT('category',true, '请选择音乐分类');
        $time_length= IT('time_length',true, '请填写音乐时长');
        $sort= IT('sort',99999);
        $check_music = Music::where(['music_name'=>$music_name,'is_delete'=>0])->first();
        if($check_music){
            return json_error('此音乐名称已存在，请重新输入');
        }
        $data =[
            'music_name' => $music_name,
            'music_link' =>clear_urlcan($music_link),
            'category'   => $category,
            'created_at'   => time2date(),
            'time_length' => $time_length,
        ];
        $music_data = Music::insertGetId($data);
        if($music_data){
            // 获取列表
            $list = Music::select(['id', 'sort'])->where([['category', '=', $category], ['status', '=', '0'], ['is_delete', '=', '0']])->orderby('sort', 'asc')->get();
            if(!empty($list)){
                $temp_arr = [];
                foreach ($list as $key=>$value) {
                    if($value->id == $music_data)
                        continue;
                    $temp_arr[$value->sort]['id'] = $value->id;
                    $temp_arr[$value->sort]['sort'] = $value->sort;
                }
                $location = $sort > 0 ? ($sort-1): 0;
                array_splice($temp_arr, $location, 0, [['id'=>$music_data, 'sort'=>$sort]]); // 插入到位置3且删除0个
                $i=1;
                foreach ($temp_arr as $k=>$val)
                    $update = Music::where('id', $val['id'])->update(['sort'=>($i++)]);
            }

            (new Log)->add($this->user, '上传了音乐' . ', 音乐名称为-'.$music_name);
            return json_success('ok');
        }else{
            return json_error('上传失败');
        }
    }

    /**
     * 音乐启用
     * @return array
     */
    public function Enable(){
        $id = trim(IT('id', true,'请输入音乐id'));
        $status = trim(IT('status',true,'请输入你要改变的状态'));

        $update= Music::where('id','=',$id)->first();
        $category = $update->category;
        $count_mumber= Music::where([['category', '=', $category],['status', '=', '0'],['is_delete', '=', '0']])->count();
        if($status ==1){
            //  Music::where('id','=',$id)->update(['sort'=>9999]);
            (new Log)->add($this->user, '修改了音乐-'.$update->music_name.'状态为-不启用');
        }elseif ($status ==0){
            $sor =$count_mumber+1;
            Music::where('id','=',$id)->update(['sort'=>$sor]);
            (new Log)->add($this->user, '修改了音乐-'.$update->music_name.'状态为-启用');
        }
        $update_date= $update->update(['status'=>$status]);
        // 重新排序
       if($update_date){
            // 获取列表
            $list = Music::select(['id', 'sort'])->where([['category', '=', $category], ['status', '=', '0'], ['is_delete', '=', '0']])->orderby('sort', 'asc')->get();
            if(!empty($list)){
                $temp_arr = [];
                foreach ($list as $key=>$value) {
                    if($value->id == $id)
                        continue;
                    $temp_arr[$value->sort]['id'] = $value->id;
                    $temp_arr[$value->sort]['sort'] = $value->sort;
                }
                $temp_arr[] = ['id'=>$id, 'sort'=>'999'];
                $i=1;
                foreach ($temp_arr as $k=>$val)
                    $update = Music::where('id', $val['id'])->update(['sort'=>($i++)]);
            }
        }
        // 处理音乐模板
        if($status == 1) {
            MusicBackGroundService::replace_background_music(['music_id' => $id]);
        }
        return json_success('ok');
    }

    /**
     * 音乐删除
     * @return array
     */
    public function DelMusic(){
        $id = IT('id',true,'请输入音乐id');
        $music = Music::where('id','=',$id)->first();
        $del_data = Music::where('id','=',$id)->update(['is_delete'=>1]);

        // 重新排序
        $list = Music::where([['category', '=', $music->category], ['status', '=', '0'], ['is_delete', '=', '0']])->orderBy('sort', 'asc')->get();
        if(!empty($list))
            $i=1;
        foreach ($list as $key=>$value)
            Music::where('id','=',$value->id)->update(['sort'=>($i++)]);

        // 处理音乐模板
        MusicBackGroundService::replace_background_music(['music_id' => $id]);


        if($del_data){
            (new Log)->add($this->user, '删除了音乐-'.$music->music_name);
            return json_success('ok');
        }else{
            return json_error('删除失败');
        }
    }
    /**
     * 音乐排序修改
     * @return array
     */
    public function UpdateSort(){

        $task_key = config('feild.redis.task.music_sort.key');
        $max_lock_time = config('feild.redis.task.music_sort.max_lock_time');
        if(!empty(Redis::get($task_key)))
            return json_error('音乐排序任务在执行，5分钟后再操作！');

        $id = IT('id', true,'请输入音乐ID');
        $sort = (int)IT('sort');
        $music_type = IT('music_type');
        $music_name = IT('music_name');

        $row = Music::where('id','=',$id)->first();
        if($row->status != '0')
            return json_error('音乐未启用，修改失败');
        if($row->is_delete != '0')
            return json_error('音乐已被删除，修改失败');
        $cheeck_music = Music::where([['id', '!=', $id], ['music_name','=',$music_name]])->first();
        if($cheeck_music)
            return json_error('音乐名称已存在！');

        // 获取列表  通过分类重新排序
        $list = Music::select(['id', 'sort'])->where([['category', '=', $music_type],  ['is_delete', '=', '0']])->orderby('sort', 'asc')->get();
        if(!empty($list) && $row->sort !== $sort){
            $temp_arr = [];
            foreach ($list as $key=>$value) {
                if($value->id == $id)
                    continue;
                $temp_arr[$value->sort]['id'] = $value->id;
                $temp_arr[$value->sort]['sort'] = $value->sort;
            }
            $location = $sort > 0 ? ($sort-1): 0;
            array_splice($temp_arr, $location, 0, [['id'=>$id, 'sort'=>$sort]]); // 插入到位置3且删除0个
            $i=1;
            foreach ($temp_arr as $k=>$val){
                $update = Music::where('id', $val['id'])->update(['sort'=>($i++)]);
            }
        }

        $music_update = [];
        $music_rule_arr = [];
        // 锁定
        if($sort != $row->sort){
            $music_update['flag'] = 1;
            $music_rule_arr[] = $music_type;
        }
        // 修改分类
        if(!empty($music_type) && ($music_type != $row->category)){
            $music_update['category'] = $music_type;
            $music_rule_arr[] = $music_type;
            $music_rule_arr[] = $row->category;
        }
        if(!empty($music_name) && ($music_name !== $row['music_name']))
            $music_update['music_name'] = $music_name;
        if(!empty($music_update))
            Music::where([['id', '=', $id]])->update($music_update);

        // 重新排序
        $music_service = new MusicService();
        $music_service->music_sort(array_unique($music_rule_arr));

        //if($update)
        (new Log)->add($this->user, '修改音乐');

        return json_success('ok');
       }

    /**
     * 音乐详情
     *
     */
    public function MusicListDetails()
    {
        $id = IT('id',true,'请输入音乐id');
        $music_data = Music::where(['id'=>$id,'is_delete'=>0])->select('id','music_name','music_link','category','time_length','sort')->first();
        $class_name = MusicType::where('id',$music_data->category)->value('name');
        $music_data->category_id = $music_data->category;
        $music_data->category = $class_name;
        return json_success('ok',$music_data);
    }

    /**
     *音乐分类的添加
     *
     */
    public function AddMusicType(){
        $name = IT('name',true,'请输入名称');
        $check_name=MusicType::where(['name'=>$name,'status'=>0])->first();
        if($check_name){
            return json_error('改名称已存在');
        }
        $insert_data= MusicType::insert(['name'=>$name,'created_at'=>time2date()]);
        if($insert_data){
            (new Log)->add($this->user, '添加了音乐分类名称为-'.$name);
            return json_success('ok');
        }else{
            return json_error('添加失败');
        }
    }

    /**
     * @return array
     * 音乐分类删除
     */
    public function DelMusicType(){
        $name = IT('name',true,'请输入id');
        $check_name=MusicType::where('name','=',$name)->first();
        if(!$check_name){
            return json_error('该类别不存在');
        }
        $insert_data= MusicType::where('name','=',$name)->update(['status'=>1]);
        if($insert_data){
            (new Log)->add($this->user, '删除了音乐分类名称为-'.$check_name->name);
            return json_success('ok');
        }else{
            return json_error('删除失败');
        }
    }

    /**
     * 音乐分类启,禁用
     */

    public function MusicTypeEnable(){
        $id= IT('id',true,'请输入音乐类型ID');
        $enable = IT('enable',true,'请输入启用，禁用数');
        $data = MusicType::where('id','=',$id)->update(['enable'=>$enable]);
        if($data){
            return json_success('ok');
        }else{
            return json_error('修改失败');
        }

    }

    /**
     * @return array
     * 音乐分类详情
     */
    public function MusicDetails()
    {
        $id= IT('id',true,'请输入音乐类型ID');
        $data =MusicType::where('id','=',$id)->first(['id','name','sort']);
        return json_success('ok',$data);
    }
    /**
     *音乐分类排序修改
     *
     */
    public function MusicSorting(){
        $id= IT('id',true,'请输入音乐类型ID');
        $name= IT('name');
        $sort = IT('sort');
        $check_Music = MusicType::where('id','=',$id)->first();
        if(!$check_Music){
            return json_error('没有该类别');
        }
        if(isset($name)){
            $update = MusicType::where('id','=',$id)->update(['name'=>$name]);
        }
        if(isset($sort)){
            MusicType::where('sort','>=',$sort)->increment('sort');
            $update = MusicType::where('id','=',$id)->update(['sort'=>$sort]);
        }
        if($update){
            (new Log)->add($this->user, '修改了音乐类别,名称为-'.$check_Music->name);
            return json_success('ok');
        }else{
            return json_error('修改失败');
        }
    }

    /**
     * @desc 添加模板音乐
     */
    public function add_background_music()
    {
        $params = [];
        $params['template_name'] = IT('template_name', true, '请输入模板名称');
        $params['music_id'] = (int)IT('music_id', true, '请选择音乐');
        $params['music_cid'] = (int)IT('music_cid', true, '请选择音乐类别');
        $params['uid'] = $this->user['id'];

        $rs = MusicBackGroundService::add_background_music($params);
        if($rs['code'] != 0) {
            return json_error($rs['msg']);
        }

        (new Log)->add($this->user, '添加模板音乐为'.json_encode($params));
        return json_success('ok');
    }

    /**
     * @desc 修改模板音乐
     */
    public function modify_background_music()
    {
        $params = [];
        $params['id'] = IT('id', true, '请选择模板音乐');
        $params['template_name'] = IT('template_name', true, '请输入模板名称');
        $params['music_id'] = (int)IT('music_id', true, '请选择音乐');
        $params['music_cid'] = (int)IT('music_cid', true, '请选择音乐类别');
        $params['uid'] = $this->user['id'];

        $rs = MusicBackGroundService::modify_background_music($params);
        if($rs['code'] != 0) {
            return json_error($rs['msg']);
        }

        (new Log)->add($this->user, '修改模板音乐【'.$params['id'].'】为'.json_encode($params));
        return json_success('ok');
    }

    /**
     * @desc 修改模板音乐状态
     */
    public function modify_background_music_status()
    {
        $params = [];
        $params['id'] = (int)IT('id', true, '请选择模板音乐');
        $params['status'] = (int)IT('status', true, '请选择模板音乐状态');
        $params['uid'] = $this->user['id'];
        $rs = MusicBackGroundService::modify_background_music_status($params);
        if($rs['code'] != 0) {
            return json_error($rs['msg']);
        }

        (new Log)->add($this->user, '修改模板音乐【'.$params['id'].'】状态为-'.$params['status']);
        return json_success('ok');
    }

    /**
     * @desc 获取模板音乐列表
     */
    public function get_background_music_list(Request $request)
    {
        $page = max(1, (int) $request->input('page'));
        $page_size = (int) $request->input('pagesize');
        $template_name = IT('template_name');
        $music_cid = IT('music_cid');

        $page_size = $page_size ?: 20;
        $offset = ($page - 1) * $page_size;
        $where_arr[] = ['is_delete', '=', 0];
        if($template_name) {
            $where_arr[] = ['template_name', 'like', '%'.$template_name.'%'];
        }
        if($music_cid) {
            $where_arr[] = ['music_cid', '=', $music_cid];
        }

        $total = MusicBackground::where($where_arr)->count();
        $fields = ['id', 'template_name', 'music_id', 'music_name', 'music_link', 'music_cid','time_length', 'created_at', 'updated_at', 'status'];
        $music_list = MusicBackground::where($where_arr)->skip($offset)->take($page_size)->orderBy('id', 'desc')->get($fields)->toArray();

        if(!empty($music_list)) {
            foreach($music_list as &$music) {
                $type_info = MusicType::where(['id' => $music['music_cid']])->first(['name']);
                $music['music_type_name'] = '';
                if($type_info) {
                    $music['music_type_name'] = $type_info->name;
                }
                $music['music_link'] = getSignUrl($music['music_link']);
            }
        }
        $total_page = ceil($total / $page_size);

        return json_success('ok', ['totalpage' => $total_page,'total'=>$total, 'list' => $music_list]);
    }

    /**
     * @desc 获取模板音乐详情
     */
    public function get_background_music_info()
    {
        $id = IT('id', true, '请选择模板音乐');
        $music_info = MusicBackground::where(['id' => $id])->first();
        if(empty($music_info)) {
            return json_error('模板音乐数据异常');
        }

        $music_info = $music_info->toArray();
        $music_info['music_type_name'] = '';
        $type_info = MusicType::where(['id' => $music_info['music_cid']])->first(['name']);
        if($type_info) {
            $music_info['music_type_name'] = $type_info->name;
        }

        $music_info['music_link'] = getSignUrl($music_info['music_link']);
        // 获取所有音乐列表
        $music_info['music_type_list'] = MusicType::where(['status'=>0,'enable'=>1])->get(['id','name'])->toArray();
        // 获取该分类的所有音乐
        $music_info['music_list'] = Music::where(['status'=>0,'is_delete'=> 0, 'category' => $music_info['music_cid']])->get(['id','music_name'])->toArray();
        return json_success('ok', $music_info);
    }

    /*
     * 推荐视频
     * */
    public function recommend(Request $request)
    {
        $params = $request->all();
        if(!isset($params['media_id']) || empty($params['media_id']))
            return json_error('请选择视频');

        $media_service = new MediaService();
        $result = $media_service->channge_media_recommend($params);
        if($result['status'] == 'error')
            return json_error($result['message']);
        (new Log)->add($this->user, '编辑视频推荐');

        return json_success('ok');
    }

    /*
     * 推荐视频列表
     * */
    public function recommend_list(Request $request)
    {
        $params = $request->all();
        $pagesize = (isset($params['pagesize']) && (int)$params['pagesize'] > 0) ? (int)$params['pagesize'] : 10;

        $media_recommend = new MediaRecommend();
        $media = new Media();
        $user = new User();

        $feilds = [
            $media_recommend->getTable().'.id',$media_recommend->getTable().'.media_id',$media_recommend->getTable().'.sort',
            $media->getTable().'.uid',$media->getTable().'.title',$media->getTable().'.is_private',
            $media->getTable().'.media',$media->getTable().'.video_length',$media->getTable().'.pv',$media->getTable().'.like',$media->getTable().'.comments',
            $media->getTable().'.share',$user->getTable().'.name'
        ];

        $where[] = [$media->getTable().'.is_delete', '=', 0];
        $where[] = [$media->getTable().'.is_private', '=', 0];
        $where[] = [$media->getTable().'.status', '=', 1];
        // 搜索
        if(isset($params['uid']) && !empty($params['uid']))
            $where[] = [$media_recommend->getTable().'.media_uid', '=', $params['uid']];
        if(isset($params['title']) && !empty($params['title']))
            $where[] = [$media->getTable().'.title', 'like', '%'.$params['title'].'%'];
        if(isset($params['name']) && !empty($params['name']))
            $where[] = [$user->getTable().'.name', '=', $params['name']];

        $media_recommend_list = $media_recommend->leftjoin($media->getTable(), $media->getTable().'.id','=', $media_recommend->getTable().'.media_id')
        ->leftjoin($user->getTable(), $user->getTable().'.id','=', $media_recommend->getTable().'.media_uid')
        ->where($media_recommend->getTable().'.status', 1)
        ->where($where)
        ->select($feilds)
        ->orderBy($media_recommend->getTable().'.sort', 'asc')
        ->paginate($pagesize);

        if(!empty($media_recommend_list))
            foreach ($media_recommend_list as $key=>&$value)
                $value['media'] = getSignUrl($value['media']);

        /*'total'=>$media_recommend_list->total(),*/
        return json_success('ok', ['totalPage' => $media_recommend_list->lastPage(),'list' =>$media_recommend_list->items() ]);
    }

    /*
     * 删除推荐视频
     * */
    public function recommend_del(Request $request)
    {
        $params = $request->all();
        if(!isset($params['media_id']) && empty($params['media_id']))
            return json_error('请选择视频');

        $media_service = new MediaService();
        $result = $media_service->del_recommend($params['media_id']);
        if($result['status'] == 'error')
            return json_error($result['message']);

        return json_success('ok');
    }

}